﻿# coding=utf-8
import time
import os,sys
import math
BASE_PATH = os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))
)
sys.path.insert(0,BASE_PATH)

from bin import get_Webdriver
from .public import Public



class User_Manage():
    def __init__(self):
        self.driver = get_Webdriver.Get_Webdriver().driver

    def jumptoUserpage(self):
        self.driver.click("link_text=>用户管理")

    def clearUserInfo(self):
        """新建用户页面清除信息"""
        self.driver.clear("css=>#username")
        self.driver.clear("css=>#pwd1")
        self.driver.clear("css=>#pwd2")
        self.driver.clear("css=>#mobile")
        self.driver.clear("css=>#email")

    def addUser(self, userName="", pwd1="", pwd2="", mobile="", email="", couponsLimit=None, outTime=None, state="0"):
        """新增用户  state！=“0” 状态即为禁用  couponsLimit  None 不限   1000/天  1000每天"""
        self.input_username(userName)
        self.input_passwd1(pwd1)
        self.input_passwd2(pwd2)
        self.input_mobile(mobile)
        self.input_email(email)
        if couponsLimit:
            self.setCouponsLimit(couponsLimit)
        if outTime:
            self.setOutTime(outTime)
        self.select_IDstase(state)
        time.sleep(0.5)
        self.submit()

    def input_username(self, usename):
        self.driver.clear("css=>#username")
        self.driver.type("css=>#username", usename)

    def input_passwd1(self, passwd1):
        self.driver.clear("css=>#pwd1")
        self.driver.type("css=>#pwd1", passwd1)

    def input_passwd2(self, passwd2):
        self.driver.clear("css=>#pwd2")
        self.driver.type("css=>#pwd2", passwd2)

    def input_mobile(self, mobile):
        self.driver.clear("css=>#mobile")
        self.driver.type("css=>#mobile", mobile)

    def input_email(self, email):
        self.driver.clear("id=>email")
        time.sleep(0.2)
        self.driver.type("id=>email", email)
        time.sleep(0.2)

    def setCouponsLimit(self, couponsLimit):
        """设置用户点券限制"""
        self.driver.click("css=>.btn.btn-white.dropdown-toggle")
        if couponsLimit.split("/")[1] == "天":
            self.driver.click("css=>a[href='javascript:getType(1);']")
            time.sleep(0.2)
            self.driver.clear("css=>#couponRest")
            self.driver.type("css=>#couponRest", couponsLimit.split("/")[0])
        elif couponsLimit.split("/")[1] == "月":
            self.driver.click("css=>a[href='javascript:getType(30);']")
            time.sleep(0.2)
            self.driver.clear("css=>#couponRest")
            self.driver.type("css=>#couponRest", couponsLimit.split("/")[0])
        else:
            self.driver.click("css=>a[href='javascript:getType(-1);']")

    def setOutTime(self,outTime):
        """设定到期时间"""
        self.driver.clear("id=>dateLimit")
        self.driver.type("id=>dateLimit", outTime)

    def select_IDstase(self, state):
        """选择用户状态"""
        if state == "1":
            self.driver.click("css=>.checkbox-inline>input[value='1']")
        if state == "0":
            self.driver.click("css=>.checkbox-inline>input[value='0']")

    def submit(self):
        """点击提交按钮"""
        self.driver.click("css=>button[onclick='saveForm()']")

    def cancle(self):
        """点击取消按钮"""
        self.driver.click("css=>button[onclick='goback()']")

    def clickblank(self):
        """点击空白处"""
        self.driver.click("css=>.panel-heading")

    def searchUserbyTelOrMail(self, param):
        """可以按照用户账号 或 手机号码精确用户"""
        self.driver.clear("id=>user_loginname")
        self.driver.type("id=>user_loginname", param)
        self.driver.click("css=>button[onclick='getUser();']")
        time.sleep(3)


    def clickAdd(self):
        """点击新增用户按钮"""
        self.driver.click("css=>a[onclick='addShow()']")

    def getUserDetails(self, TelOrMail):
        time.sleep(2)
        self.searchUserbyTelOrMail(TelOrMail)
        sTelOrMail = self.driver.get_text("xpath=>.//*/td[2]")
        print(sTelOrMail)
        if sTelOrMail:
            if sTelOrMail == TelOrMail:
                self.driver.click("css=>.like[title='修改']")
                userDetailsList = []
                corporateName = self.driver.get_attribute("id=>formSave", "value")
                userName = self.driver.get_attribute("id=>username", "value")
                password = self.driver.get_attribute("id=>pwd1", "value")
                telPhone = self.driver.get_attribute("id=>mobile", "value")
                email = self.driver.get_attribute("id=>email", "value")
                couponsLimit = self.driver.get_text("id=>fieldVal")
                couponsValue = self.driver.get_attribute("id=>couponRest", "value")
                couponsBalance = self.driver.get_attribute("id=>coupon", "value")
                outTime = self.driver.get_attribute("id=>dateLimit", "value")
                userDetailsList.append(corporateName)
                userDetailsList.append(userName)
                userDetailsList.append(password)
                userDetailsList.append(telPhone)
                userDetailsList.append(email)
                userDetailsList.append(couponsLimit)
                userDetailsList.append(couponsValue)
                userDetailsList.append(couponsBalance)
                userDetailsList.append(outTime)
                return userDetailsList
        else:
            return '用户列表为空'

    def get_ErrorMsg(self):
        """获取出错信息提示，仅支持单一输入框校验 输入错误用例后务必再次输入正确用例 以便校验下一个 输入框"""
        try:
            errorMsg=self.driver.get_text("css=>.formErrorContent")
        except:
            raise TimeoutError("提示框出现超时或无提示框出现")
        else:
            return errorMsg

    def getallUserCount(self):
        """获取当前所有用户个数"""
        time.sleep(3)
        try:
            return int(self.driver.get_text('css=>.pagination-info').split(" ")[5])
        except IndexError:
            return "文件列表为空"

    def getUserCount(self):
        """获取当前页面用户个数"""
        time.sleep(3)
        try:
            number = int(self.driver.get_text('css=>.pagination-info').split(" ")[3]) - int(self.driver.get_text('css=>.pagination-info').split(" ")[1]) + 1
        except IndexError:
            return "文件列表为空"
        else:
            return number

    def getAllUserlist(self):
        """返回所有用户列表详情 list格式  用户信息空格分割 最多返回100条"""
        userList = []
        alluserNumber = self.getallUserCount()
        if alluserNumber == "用户列表为空":
            return "用户列表为空"
        totalPageNumber = math.ceil(alluserNumber / 10)
        print(totalPageNumber)
        currentPageNumber = 1
        while 1:
            if currentPageNumber > totalPageNumber:
                break
            else:
                currentuserNumber = self.getUserCount()
                for i in range(1, currentuserNumber+1):
                    username = self.driver.get_text("xpath=>.//*[@id='maingrid']/tbody/tr[{}]/td[1]".format(i))
                    usermobile = self.driver.get_text("xpath=>.//*[@id='maingrid']/tbody/tr[{}]/td[2]".format(i))
                    useremail = self.driver.get_text("xpath=>.//*[@id='maingrid']/tbody/tr[{}]/td[3]".format(i))
                    userList.append([username, usermobile, useremail])
                currentPageNumber += 1
                try:
                    self.clickNextPageButton()
                except:
                    pass
                time.sleep(5)
        return userList


    def getUserlist(self):
        """返回当前页面用户列表详情 list格式  用户信息空格分割 """
        userList = []
        currentuserNumber = self.getUserCount()
        if currentuserNumber == "用户列表为空":
            return "用户列表为空"
        for i in range(1, currentuserNumber+1):
            username = self.driver.get_text("xpath=>.//*[@id='maingrid']/tbody/tr[{}]/td[1]".format(i))
            usermobile = self.driver.get_text("xpath=>.//*[@id='maingrid']/tbody/tr[{}]/td[2]".format(i))
            useremail = self.driver.get_text("xpath=>.//*[@id='maingrid']/tbody/tr[{}]/td[3]".format(i))
            userList.append([username, usermobile, useremail])
        return userList

    def deleteUser(self,parma):
        """可以按照用户账号 或 手机号码精确删除用户"""
        self.searchUserbyTelOrMail(parma)
        time.sleep(5)
        self.driver.click("css=>.remove")
        Public().clickOKButton()
        time.sleep(1)

    def inUserLogPage(self, parma):
        self.searchUserbyTelOrMail(parma)
        time.sleep(5)
        self.driver.click("css=>.like[title='查看账号日志']")

    def get_title(self):
        return self.driver.get_text("css=>.name_uesr")


    def chooseNumberOfPage(self,number):
        """选择每页条数"""
        if number == "10":
            index = "1"
        elif number == "25":
            index = "2"
        elif number == "50":
            index = "3"
        else:
            return "每页条数不对"
        self.driver.click("")
        self.driver.click("css=>.btn.btn-default.dropdown-toggle")
        self.driver.click("xpath=>.//*[@role='menu']/li[{}]".format(index))

    def getNumberOfPage(self):
        pageNo = self.driver.get_text("css=>.page-number.active>a")
        return pageNo

    def clickNextPageButton(self):
        self.driver.click("xpath=>.//*[@class='page-next']/a")

    # def getCurrentUserList(self):
    #     """返回用户列表详情 list格式 标题\n分割  用户信息空格分割 最多返回10条"""
    #     userNumber = self.getUserCount()
    #     # print(userNumber)
    #     if userNumber == "用户列表为空":
    #         return "用户列表为空"
    #     # userTitle=self.dr.find_elements_by_xpath(ReadConfig().userListTitle_text_xpath)
    #     userList=[]
    #     # for i in userTitle:
    #     #     userList.append(i.text)
    #     # time.sleep(2)
    #     tElements = self.dr.find_elements_by_xpath(".//*[@id='maingrid']/tbody/tr")
    #     for tElement in tElements:
    #         userList.append(tElement.text)
    #     # for i in range((userNumber)):
    #     #     userId=self.dr.find_elements_by_xpath(".//*[@id='maingrid']/tbody/tr[{}]".format(str(i+1)))
    #     #     for j in userId:
    #     return userList
    #

    # def editUser(self,parma,username=None,password=None,couponsLimit=None,outTime=None,state="0"):
    #     """可以按照手机号码或邮箱精确检索并点选用户并进行编辑"""
    #     self.clickUser(parma)
    #     self.dr.find_element_by_xpath(ReadConfig().edit_button_xpath).click()
    #     time.sleep(1)
    #     # 邮箱不可编辑 20171116
    #     # if email != None:self.input_email(email)
    #     # time.sleep(0.5)
    #     if username != None:self.input_username(username)
    #     time.sleep(0.5)
    #     if password != None:self.input_password(password)
    #     time.sleep(0.5)
    #     if couponsLimit !=None:
    #         self.setCouponsLimit()
    #     time.sleep(0.5)
    #     if outTime !=None:
    #         self.setOutTime()
    #     if state != "0": state ="1"
    #     self.select_IDstase(state)
    #     time.sleep(0.5)
    #     self.submit()
    #
    # def clickUser(self,param):
    #     """可以按照用户手机号码 或 邮箱精确检索并点选用户"""
    #     self.searchUserbyTelOrMail(param)
    #     time.sleep(2)
    #     tElement=self.dr.find_element_by_xpath(ReadConfig().fristUserID_text_xpath)
    #     if tElement.text != ReadConfig().noFindUser_message_text:
    #         tElement.click()
    #     else:raise UserWarning("根据给定的额信息，没有找到匹配的用户")
    #
    #
    #
    # # def input_loginName(self,loginName):
    # #     """填写用户账号"""
    # #     self.dr.find_element_by_xpath(self.r.loginName_input_xpath).clear()
    # #     time.sleep(0.3)
    # #     self.dr.find_element_by_xpath(self.r.loginName_input_xpath).send_keys(loginName)
    #

    #
    #
    # def click_backButton(self):
    #     """点击返回按钮"""
    #     self.dr.find_element_by_xpath(self.r.return_button_xpath).click()
    #

    #
    # def isEditPage(self):
    #     return ("view=edit&action=add" in self.dr.current_url  )
    #
    #
    # def isUserLogPage(self):
    #     return ("log_detail.html?userId" in self.dr.current_url)

if __name__ == '__main__':
    pass
